package org.qydjk.console.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.user.UserExaminationPopulation;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.console.vo.UserExaminationPopulationBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lanan on 2017/12/19 0019.
 */
@Controller
@RequestMapping("/user/examination/population")
public class UserExaminationPopulationController extends BaseController {

    /**
     * 页面
     * @return 页面地址
     */
    @RequestMapping("/index.do")
    public String examinationPopulationIndex() {
        return "/user/examinationPopulation/userExaminationPopulation";
    }

    /**
     * 列表
     * @return 数据
     */
    @RequestMapping("/list.do")
    @ResponseBody
    public Object examinationPopulationList(int page, int rows) {
        List<UserExaminationPopulation> userExaminationPopulations = new ArrayList<UserExaminationPopulation>();
        Integer total = 0;
        String sql = "SELECT uep.*, u.username as user_name, u.phone as user_phone, u.email as user_email " +
                "FROM qy_user_examination_population uep " +
                "LEFT JOIN qy_user u " +
                "ON uep.user_id = u.id " +
                "WHERE 1 = 1";
        String countSql = "SELECT COUNT(uep.id) " +
                "FROM qy_user_examination_population uep " +
                "LEFT JOIN qy_user u " +
                "ON uep.user_id = u.id " +
                "WHERE 1 = 1";

        sql += handleSearchWhereStr();
        countSql += handleSearchWhereStr();

        sql += " order by update_time desc";

        try {
            userExaminationPopulations = baseService.findBeanBySQL(sql, UserExaminationPopulationBean.class, new HibernatePage(page, rows));
            total = baseService.getRecordCountSQL(countSql);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new EasyUIResponse(total, userExaminationPopulations);
    }

    /**
     * 处理查询时的条件信息
     * @return sql 条件字符串
     */
    private String handleSearchWhereStr() {
        String whereStr = "";
        String userId = request.getParameter("userId");
        String searchKeyInfo = request.getParameter("searchKeyInfo");

        if (!StringUtil.isEmptyOrNull(userId)) {
            whereStr += " and uep.user_id = " + userId;
        }
        if (!StringUtil.isEmptyOrNull(searchKeyInfo)) {
            whereStr += " and (uep.name like '%" + searchKeyInfo + "%'" +
                        " or uep.phone like '%" + searchKeyInfo + "%'" +
                        " or uep.identity like '%" + searchKeyInfo + "%')";
        }
        return whereStr;
    }

    /**
     * 添加弹框
     * @return 弹框地址
     */
    @RequestMapping("/insert/index.do")
    public String examinationPopulationInsertIndex() {
        return "/user/examinationPopulation/userExaminationPopulationInsert";
    }

    /**
     * 添加处理
     * @param userExaminationPopulation 添加数据
     * @return 处理结果
     */
    @RequestMapping("/insert.do")
    @ResponseBody
    public Object examinationPopulationInsert(UserExaminationPopulation userExaminationPopulation) {
        return handleSaveOrUpdate(true, userExaminationPopulation, "添加");
    }

    /**
     * 修改页面
     * @return 页面地址
     */
    @RequestMapping("/update/index.do")
    public String examinationPopulationUpdateIndex() {
        Integer id = Integer.valueOf(request.getParameter("id"));
        try {
            String sql = "SELECT uep.*, u.username as user_name, u.phone as user_phone, u.email as user_email " +
                    "FROM qy_user_examination_population uep " +
                    "LEFT JOIN qy_user u " +
                    "ON uep.user_id = u.id " +
                    "WHERE uep.id = " + id;
            List<UserExaminationPopulationBean> userExaminationPopulations = baseService.findBeanBySQL(sql, UserExaminationPopulationBean.class);
            UserExaminationPopulation userExaminationPopulation = new UserExaminationPopulation();
            if (userExaminationPopulations.size() > 0) {
                userExaminationPopulation = userExaminationPopulations.get(0);
            }
            request.setAttribute("userExaminationPopulation", userExaminationPopulation);
            return "/user/examinationPopulation/userExaminationPopulationUpdate";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改处理
     * @param userExaminationPopulation 添加数据
     * @return 处理结果
     */
    @RequestMapping("/update.do")
    @ResponseBody
    public Object examinationPopulationUpdate(UserExaminationPopulation userExaminationPopulation) {
        return handleSaveOrUpdate(false, userExaminationPopulation, "修改");
    }

    /**
     * 合并处理添加和修改
     * @param isSave true:添加  false:修改
     * @param userExaminationPopulation 操作数据
     * @param msg 修改还是添加
     * @return 处理结果
     */
    private Object handleSaveOrUpdate(Boolean isSave, UserExaminationPopulation userExaminationPopulation, String msg) {
        JSONObject resp = new JSONObject();
        if (userExaminationPopulation.getUserId() == null) {
            resp.put("success", false);
            resp.put("msg", "用户不存在或操作错误！");
        } else {
            // 如果该用户已有该类卡账户
            if (theUserThePopulationHadUse(userExaminationPopulation)) {
                resp.put("success", false);
                if (isSave) resp.put("msg", "该用户下该常用联系人已存在，添加失败");
                else resp.put("msg", "该用户下该常用联系人已存在，修改失败！");
                return JSON.toJSON(resp);
            }
            try {
                if (userExaminationPopulation.getDef() != null && userExaminationPopulation.getDef() == 1) {
                    String sql = "update qy_user_examination_population " +
                            "set def = '0' " +
                            "where def = '1' " +
                            "and user_id = " + userExaminationPopulation.getUserId();
                    baseService.excuteSQL(sql);
                }
                userExaminationPopulation.setUpdateTime(new Date());
                if (isSave) {
                    userExaminationPopulation.setCreateTime(new Date());
                    baseService.save(userExaminationPopulation);
                } else {
                    UserExaminationPopulation uda = baseService.get(UserExaminationPopulation.class, userExaminationPopulation.getId());
                    BeanUtil.copyProperties(userExaminationPopulation, uda);
                    baseService.update(uda);
                }
                resp.put("success", true);
                resp.put("msg", msg);
            } catch (Exception e) {
                e.printStackTrace();
                resp.put("success", false);
                resp.put("msg", e.toString());
            }
        }
        return JSON.toJSON(resp);
    }

    /**
     * 判断该用户是否拥有当前操作常用联系人
     * @param userExaminationPopulation 前端提交数据
     * @return true:已有  false:没有
     */
    private boolean theUserThePopulationHadUse(UserExaminationPopulation userExaminationPopulation) {
        String sql = "select id from qy_user_examination_population where user_id = '" + userExaminationPopulation.getUserId() + "'";
        Integer id = null;
        sql += " and identity = '" + userExaminationPopulation.getIdentity() + "'";
        try {
            id = baseService.getUniqueResultSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        if (id == null || id == userExaminationPopulation.getId()) {
            return false;
        }
        return true;
    }


    /**
     * 删除操作
     * @param userExaminationPopulation 待处理数据
     * @return 处理结果
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object examinationPopulationDelete(UserExaminationPopulation userExaminationPopulation) {
        JSONObject resp = new JSONObject();
        Integer id = userExaminationPopulation.getId();
        if(id == null || id == 0){
            resp.put("success", false);
            resp.put("msg", "id不能为空！");
        } else {
            try {
                resp.put("success", true);
                baseService.delete(userExaminationPopulation);
            } catch (Exception e) {
                resp.put("success", false);
                resp.put("msg", e.toString());
            }
        }
        return JSON.toJSON(resp);
    }
}
